package jplat.tools.config;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import jplat.base.constant.KPlatResponseCode;
import jplat.base.constant.KTraceLog;
import jplat.error.exception.JSystemException;
import jplat.tools.string.JLogUtils;
import jplat.tools.string.StringUtil;
import jplat.tools.string.XLog;

/**
 * 数据库或者缓存相关文件初始化.
 * @author zhangcq
 * @date Jan 4, 2017
 * @comment
 */
public class JDataBaseConfig
{
	public boolean isOk = true;
	private Properties prop = null;
	
	private static final String confPath = "conf/database/qdbase.properties";
//	private static final String confPath = "a/autocode/app/port/backup/loginDemo.port";
	
	private static final class Holer
	{
		private static final JDataBaseConfig config = new JDataBaseConfig();
	}
	
	private JDataBaseConfig()
	{
		init();
	}
	
	public void init()
	{
		prop=JConfigUtils.loadPropertis(confPath);
		/*
		InputStream is = getClass().getClassLoader().getResourceAsStream(confPath);
		prop = new Properties();
		try {
			prop.load(is);
			is.close();
			
			XLog.log(JLogUtils.getTraceLog(KTraceLog.ACTION_JINIT, KTraceLog.EVENT_SUCCESS, "", "load:"+confPath));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	*/}
	
	public static final JDataBaseConfig getInstance()
	{
		return Holer.config;
	}
	
	public String getString( String key, boolean must ) throws JSystemException
	{
		String value = prop.getProperty(key);
		if ( must && StringUtil.isEmpty(value) )
		{
			throw new JSystemException(KPlatResponseCode.CD_CONF_NOT_FOUND,KPlatResponseCode.MSG_CONF_NOT_FOUND);
		}
		
		return value;
	}
	
	/**
	 * @author zhangcq
	 * @date Jan 4, 2017
	 * @comment 
	 * @param key
	 * @param defval
	 * @return
	 */
	public String getString( String key, String defStr )
	{
		String value = prop.getProperty(key);
		if( StringUtil.isEmpty(value) )
		{
			return defStr;
		}
		
		return value;
	}
	
	public int getInt( String key, int defInt )
	{
		return Integer.parseInt(getString(key,""+defInt));
	}
	
	public int getInt( String key, boolean must ) throws JSystemException
	{
		return Integer.parseInt(getString(key,must));
	}
	
	public static void main(String args[])
	{
		JDataBaseConfig config = new JDataBaseConfig();
		XLog.log(config.getString("redis.password","not found"));
	}
}
